package vn.com.shoppie.activity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.RejectedExecutionException;

import org.apache.http.client.ClientProtocolException;

import vn.com.shoppie.activity2.BrandActivity2;
import vn.com.shoppie.network.WiModelManager;
import vn.com.shoppie.object.AsynBluetooth;
import vn.com.shoppie.object.MainAdapter;
import vn.com.shoppie.object.MyPositionOverlay;
import vn.com.shoppie.object.ShopOverlay;
import vn.com.shoppie.object.ShopOverlayItem;
import vn.com.shoppie.object.ShopOverlayItem.OnOverlayTap;
import vn.com.shoppie.object.StoreAdapter;
import vn.com.shoppie.setting.SettingPreference;
import vn.com.shoppie.sobject.Campaign;
import vn.com.shoppie.sobject.Merchant;
import vn.com.shoppie.sobject.Shop;
import vn.com.shoppie.sobject.ShoppieObject;
import vn.com.shoppie.sobject.Store;
import vn.com.shoppie.sobjmng.MerchantMng;
import vn.com.shoppie.util.SConfig;
import vn.com.shoppie.util.SUtil;
import vn.com.shoppie.util.SUtilXml;
import vn.com.shoppie.util.StoreComparator;
import vn.com.shoppie.view.ActionItem;
import vn.com.shoppie.view.QuickAction;
import vn.com.shoppie.view.QuickAction.OnActionItemClickListener;
import vn.com.shoppie.view.ShopMapView;
import vn.com.shoppie.view.ShopMapView.ZoomListener;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SlidingDrawer;
import android.widget.SlidingDrawer.OnDrawerCloseListener;
import android.widget.SlidingDrawer.OnDrawerOpenListener;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class MainActivity extends MapActivity implements OnActionItemClickListener, OnOverlayTap, LocationListener, ZoomListener {

	boolean isMapOpened = false;
	LocationManager mLocaMng;

	private Gallery glrShopIcon;
	private ShopMapView mMapShops;
	private MapController myMapController;
	private ImageView currentPosOnMap;
	private SlidingDrawer mSdMapShop;
	private ImageButton mSdHandler;
	private LinearLayout mSdContent;
	private FrameLayout mFrStore;
	private RelativeLayout mRltStore;
	private RelativeLayout mLyLstStore;
	private ImageView mBtnMapStore;
	private ListView mLstStore;

	ArrayList<ShoppieObject> data = new ArrayList<ShoppieObject>();
	ArrayList<ShoppieObject> stores = new ArrayList<ShoppieObject>();
	MainAdapter mAdapterShop;
	StoreAdapter mAdapterStore;
	List<Overlay> mapOverlays;

	public static GeoPoint myLocation = new GeoPoint(21004269, 105845910);	// default : bkhn
	public static float accurancy = 0;
	public static int zoom = 18;
	public static int zoom_def = 18;
	OverlayItem myOverlayItem;
	MyPositionOverlay myOverlay;
	ShopOverlay shopsOverlay;
	Handler mHandler;

	// quick Action
	QuickAction quickAction;
	private static final int ID_UP = 1, ID_DOWN = 2, ID_SEARCH = 3, ID_INFO = 4, ID_ERASE = 5, ID_OK = 6;
	ActionItem nextItem, prevItem, searchItem, infoItem, eraseItem, okItem;

	int lastIndex = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		mHandler = new Handler();

		glrShopIcon = (Gallery) findViewById(R.id.glr_icon_shop);
		mMapShops = (ShopMapView) findViewById(R.id.mapview);
		mSdMapShop = (SlidingDrawer) findViewById(R.id.sd_map);
		mSdHandler = (ImageButton) findViewById(R.id.sd_handler);
		// mSdContent = (LinearLayout) findViewById(R.id.sd_content);
		mRltStore = (RelativeLayout) findViewById(R.id.rlt_store);
		mFrStore = (FrameLayout) findViewById(R.id.frly_Store);
		mLyLstStore = (RelativeLayout) findViewById(R.id.ly_lst_store);
		mBtnMapStore = (ImageView) findViewById(R.id.btn_map_list_store);
		mLstStore = (ListView) findViewById(R.id.lst_store);
		myMapController = mMapShops.getController();
		currentPosOnMap = new ImageView(mMapShops.getContext());

		initView();
		mAdapterStore = new StoreAdapter(this, stores);
		mLstStore.setAdapter(mAdapterStore);
		mMapShops.setZoomListener(this);

		mSdMapShop.setOnDrawerOpenListener(new OnDrawerOpenListener() {

			@Override
			public void onDrawerOpened() {
				mSdHandler.post(new Runnable() {

					@Override
					public void run() {
						mSdHandler.setBackgroundColor(Color.BLACK);
						mSdHandler.getBackground().setAlpha(200);
						isMapOpened = true;
					}
				});
			}
		});
		mSdMapShop.setOnDrawerCloseListener(new OnDrawerCloseListener() {

			@Override
			public void onDrawerClosed() {
				mSdHandler.post(new Runnable() {

					@Override
					public void run() {
						mSdHandler.getBackground().setAlpha(255);
						mSdHandler.setBackgroundColor(Color.TRANSPARENT);
						isMapOpened = false;
					}
				});
			}
		});

		// refresh
		drawMyLocation(myLocation, 20);
		refreshUI();

		// LOCATION
		mLocaMng = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

		try {
			mLocaMng.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 0, 0, this);
			mLocaMng.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
			mLocaMng.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
		} catch (IllegalArgumentException e) {

		}

		glrShopIcon.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
				lastIndex = position;
				showToast("item:" + ((Campaign) data.get(position)).name);
				Intent brandIntent = new Intent(MainActivity.this, BrandActivity2.class);
				brandIntent.putExtra(BrandActivity.MERCH_ID, ((Campaign) data.get(position)).merchId);
				brandIntent.putExtra(BrandActivity.CAMPAIGN, ((Campaign) data.get(position)));
				startActivity(brandIntent);
			}
		});

		bgrProcessing();
	}

	public void initView() {
		// QUICK ACTION
		quickAction = new QuickAction(this, QuickAction.HORIZONTAL);

		nextItem = new ActionItem(ID_DOWN, "Next", getResources().getDrawable(R.drawable.menu_down_arrow));
		prevItem = new ActionItem(ID_UP, "Prev", getResources().getDrawable(R.drawable.menu_up_arrow));
		searchItem = new ActionItem(ID_SEARCH, "Find", getResources().getDrawable(R.drawable.menu_search));
		infoItem = new ActionItem(ID_INFO, "Info", getResources().getDrawable(R.drawable.menu_info));
		eraseItem = new ActionItem(ID_ERASE, "Clear", getResources().getDrawable(R.drawable.menu_eraser));
		okItem = new ActionItem(ID_OK, "OK", getResources().getDrawable(R.drawable.menu_ok));

		prevItem.setSticky(true);
		nextItem.setSticky(true);

		quickAction.addActionItem(nextItem);
		quickAction.addActionItem(prevItem);
		quickAction.addActionItem(searchItem);
		quickAction.addActionItem(infoItem);
		quickAction.addActionItem(eraseItem);
		quickAction.addActionItem(okItem);

		quickAction.setOnActionItemClickListener(this);

		// MAPVIEW
		currentPosOnMap.setImageResource(R.drawable.ico_map_anim);
		mMapShops.setBuiltInZoomControls(true);
		mapOverlays = mMapShops.getOverlays();
		currentPosOnMap.post(new Runnable() {
			@Override
			public void run() {
				AnimationDrawable animationDrawable = (AnimationDrawable) currentPosOnMap.getDrawable();
				animationDrawable.start();
			}
		});
		mMapShops.addView(currentPosOnMap);

		// My location
		Drawable drawable = this.getResources().getDrawable(R.drawable.ico_map_anim);
		myOverlay = new MyPositionOverlay(this, drawable, myLocation, 200);
		mapOverlays.add(myOverlay);

		// add new point to map
		Drawable shopDrawable = this.getResources().getDrawable(R.drawable.ico_map_flag_red);
		shopsOverlay = new ShopOverlay(this, shopDrawable);

		// SHOPPIE
		data = new ArrayList<ShoppieObject>();
		stores = new ArrayList<ShoppieObject>();
		mAdapterStore = new StoreAdapter(this, stores);
		mAdapterStore.notifyDataSetChanged();
		mLstStore.setAdapter(mAdapterStore);
	}

	public void addStoreToMap(Store store) {
		ShopOverlayItem overlayitem = new ShopOverlayItem(this, store, this);
		shopsOverlay.addOverlay(overlayitem);
		mapOverlays.add(shopsOverlay);
		myMapController.animateTo(store.getLocation());
	}

	public void addStoreToMap(ArrayList<Store> stores) {
		ArrayList<ShopOverlayItem> items = new ArrayList<ShopOverlayItem>();
		for (Store store : stores) {
			try {
				ShopOverlayItem overlayitem = new ShopOverlayItem(this, store, this);
				// overlayitem.refreshDrawable(MainActivity.zoom);
				items.add(overlayitem);
			} catch (RejectedExecutionException e) {
				e.printStackTrace();
			}
		}

		shopsOverlay.addOverlays(items);
		mapOverlays.add(shopsOverlay);
	}

	public void drawMyLocation(GeoPoint geoPoint, float radius) {
		// add new point to map

		myOverlay.removeAllOverlay();
		myOverlay.setRadius(radius);
		myOverlayItem = new OverlayItem(geoPoint, "My Locate", geoPoint.toString());
		myOverlay.addOverlay(myOverlayItem);

		MapView.LayoutParams layoutParams = new MapView.LayoutParams(MapView.LayoutParams.WRAP_CONTENT, MapView.LayoutParams.WRAP_CONTENT, geoPoint, MapView.LayoutParams.BOTTOM_CENTER);
		currentPosOnMap.setLayoutParams(layoutParams);
		myMapController.animateTo(geoPoint);
		mMapShops.invalidate();
	}

	static boolean fistUse = true;

	public void refreshUI() {

		// MERCHAMPAIGNS
		String url = SConfig.URL_SHOPPIE_HOME + SConfig.URL_MERCHCAMPAIGNS;
		new AsyncTask<String, Integer, String>() {
			WiModelManager mng = new WiModelManager();

			@Override
			protected String doInBackground(String... arg0) {
				String xml = null;
				try {

					xml = SUtilXml.getInstance().getXmlFromLink(MainActivity.this, arg0[0]);
					mng.parse(xml);
				} catch (ClientProtocolException e) {
					if (SettingPreference.PRINT_STACK_TRACE) {
						e.printStackTrace();
					}
					System.out.println(e.toString());
				} catch (IOException e) {
					if (SettingPreference.PRINT_STACK_TRACE) {
						e.printStackTrace();
					}
					System.out.println(e.toString());
				}
				return xml;
			}

			protected void onPostExecute(String xml) {

				data = mng.getResultShoppieObject();
				mAdapterShop = new MainAdapter(MainActivity.this, data);
				glrShopIcon.setAdapter(mAdapterShop);
				if (fistUse) {
					// fistUse=false;
					if (lastIndex >= data.size())
						lastIndex = 0;
					glrShopIcon.setSelection(lastIndex, true);
				}
			};
		}.execute(url);

		// STORE
		String urlStore = SConfig.URL_SHOPPIE_HOME + SConfig.URL_ALL_STORE;
		new AsyncTask<String, Integer, String>() {
			WiModelManager mng = new WiModelManager();

			@Override
			protected String doInBackground(String... arg0) {
				String xml = null;
				try {
					xml = SUtilXml.getInstance().getXmlFromLink(MainActivity.this, arg0[0]);
					mng.parse(xml);
				} catch (ClientProtocolException e) {
					if (SettingPreference.PRINT_STACK_TRACE) {
						e.printStackTrace();
					}
					System.out.println(e.toString());
				} catch (IOException e) {
					if (SettingPreference.PRINT_STACK_TRACE) {
						e.printStackTrace();
					}
					System.out.println(e.toString());
				}

				return xml;
			}

			protected void onPostExecute(String xml) {
				stores = mng.getResultShoppieObject();
				Collections.sort(stores, new StoreComparator());
				// Map Store
				ArrayList<Store> _stores = new ArrayList<Store>();

				for (ShoppieObject object : stores) {
					Store store = (Store) object;
					_stores.add(store);
				}
				Log.e("addStoreToMap", _stores.size() + "stores");
				addStoreToMap(_stores);

				// List Store
				if (mAdapterStore == null)
					mAdapterStore = new StoreAdapter(MainActivity.this, stores);
				mAdapterStore = new StoreAdapter(MainActivity.this, stores);
				mLstStore.setAdapter(mAdapterStore);
				mAdapterStore.notifyDataSetChanged();
			};
		}.execute(urlStore);

		try {
			Location location = mLocaMng.getLastKnownLocation(LocationManager.GPS_PROVIDER);
			if (location == null) {
				location = mLocaMng.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
				if (location == null) {
					location = mLocaMng.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
					if (location == null) {
						return;
					}
				}
			}
			MainActivity.myLocation = new GeoPoint((int) (location.getLatitude() * 1E6), (int) (location.getLongitude() * 1E6));
			myMapController.animateTo(MainActivity.myLocation);
		} catch (NullPointerException ex) {
		}

		drawMyLocation(MainActivity.myLocation, MainActivity.accurancy);
	}

	@Override
	protected void onResume() {
		super.onResume();
		getLastKnownLocation();
		refreshUI();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	public void showBluetoothDialog() {
		AsynBluetooth bluetoothAsyn = new AsynBluetooth(this, 20);
		bluetoothAsyn.execute();

		// BluetoothDialog bluetooth=new BluetoothDialog(this);
		// bluetooth.show();

		// startActivity(new Intent(this, BluetoothExample.class));
	}

	public void btnClicked(View v) {
		switch (v.getId()) {
		case R.id.btn_personal:
			startActivity(new Intent(this, ProfileActivity.class));
			break;
		case R.id.btn_pie:
			new AsynBluetooth(this, 120).execute("");
			// show bluetooth dialog
			// showBluetoothDialog();
			// startActivity(new Intent(this, BrandActivity2.class));
			break;
		case R.id.btn_move:
			try {
				Location location = mLocaMng.getLastKnownLocation(LocationManager.GPS_PROVIDER);
				if (location == null) {
					location = mLocaMng.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
					if (location == null) {
						location = mLocaMng.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
						if (location == null) {
							return;
						}
					}
				}
				MainActivity.myLocation = new GeoPoint((int) (location.getLatitude() * 1E6), (int) (location.getLongitude() * 1E6));
				myMapController.animateTo(MainActivity.myLocation);
			} catch (NullPointerException ex) {
			}
			drawMyLocation(myLocation, MainActivity.accurancy);
			myMapController.setZoom(MainActivity.zoom_def);
			break;
		case R.id.btn_gift:
			startActivity(new Intent(this, GiftActivity.class));

			break;
		case R.id.btn_showMap:
			mRltStore.setVisibility(View.VISIBLE);
			mLstStore.setVisibility(View.GONE);
			break;
		case R.id.btn_showStore:
			mRltStore.setVisibility(View.GONE);
			mLstStore.setVisibility(View.VISIBLE);
			break;
		case R.id.btn_map_list_store:
			if (mRltStore.getVisibility() == View.VISIBLE) {
				mRltStore.setVisibility(View.GONE);
				mLstStore.setVisibility(View.VISIBLE);
			} else {
				mRltStore.setVisibility(View.VISIBLE);
				mLstStore.setVisibility(View.GONE);
			}
			break;
		default:
			break;
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			if (isMapOpened) {
				this.mSdMapShop.animateClose();
				isMapOpened = !isMapOpened;
				return true;
			}

		}

		return super.onKeyDown(keyCode, event);
	}

	// create data
	public ArrayList<Shop> createDataSample() {
		ArrayList<Shop> data = new ArrayList<Shop>();
		for (int i = 0; i < 11; i++) {
			Shop item = null;
			if (i % 2 == 0) {
				String[] values = { R.drawable.cocacola + "", "Cocacola" + i, "", "", "" };

				item = new Shop(-1, values);
				item.desc = "uong cocacola ngon lam" + i;
				item.discount = i * 10;
			} else {
				String[] values = { R.drawable.doraemon + "", "Cocacola" + i, "", "", "" };
				item = new Shop(-1, values);
				item.desc = "truyen tranh doraemon hay lam" + i;
				item.discount = i * 10;
			}
			data.add(item);
		}
		return data;
	}

	// BACKGROUND PROCESSING
	private void bgrProcessing() {
		// REGISTER ACCOUNT - SEND BLUETOOTH ID
		String deviceID = SUtil.getInstance().getDeviceId(this);
		if (deviceID.equals(""))
			return;
		SettingPreference.setUserDeviceToken(this, deviceID);
		new AsyncTask<String, Void, Boolean>() {
			int timeOut = 120;
			int count = 0;
			String bltId;
			BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();

			@Override
			protected Boolean doInBackground(String... arg0) {
				if (register())
					return true;
				if (adapter == null)
					return false;
				boolean firstState = adapter.isEnabled();
				count = 0;
				while (count < timeOut) {
					count++;
					if (!adapter.isEnabled()) {
						adapter.isEnabled();

					}
					if (!adapter.isDiscovering()) {
						adapter.startDiscovery();
					}
					bltId = adapter.getAddress();
					if (bltId != null && bltId.equals("")) {
						SettingPreference.setUserCode(getApplicationContext(), bltId);
						break;
					}
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
					}
				}
				if (!firstState)
					adapter.disable();
				register();
				return false;
			}

			private boolean register() {
				String deviceID = SettingPreference.getUserDeviceToken(getApplicationContext());
				String customCode = SettingPreference.getUserCode(getApplicationContext());
				if (!deviceID.equals("") && !customCode.equals("")) {
					int userID = SUtilXml.getInstance().registerAccount(getApplicationContext(), deviceID, customCode);
					if (userID > -1) {
						showToast("User ID:" + userID);
						return true;
					}
				}
				return false;
			}
		};
		// new AsynBluetooth(this, 120).execute("");

		// LOAD MERCHANTS
		new AsyncTask<String, Void, Boolean>() {
			@Override
			protected Boolean doInBackground(String... arg0) {

				String merchants = SConfig.URL_SHOPPIE_HOME + SConfig.URL_MERCHANTS;
				System.out.println("Load merchants: " + merchants);
				try {
					String xml = SUtilXml.getInstance().getXmlFromLink(getApplicationContext(), merchants);
					WiModelManager mng = new WiModelManager();
					// System.out.println("do in background LoadMerchant response:"+xml);
					if (xml.contains("error")) {
						System.out.println("Error getxml from merchant");
						return false;
					}
					mng.parse(xml);
					ArrayList<ShoppieObject> dataMerchants = mng.getResultShoppieObject();
					MerchantMng mcMng = new MerchantMng(getApplicationContext());
					ArrayList<Merchant> mcData = mcMng.select();
					ArrayList<Integer> arrayId = new ArrayList<Integer>();
					for (ShoppieObject item : dataMerchants) {
						for (Merchant mcItem : mcData) {
							if (((Merchant) item).merchId.equals(mcItem.merchId)) {
								arrayId.add(dataMerchants.indexOf(item));
							}
						}
					}
					for (int i = arrayId.size() - 1; i >= 0; i--) {
						dataMerchants.remove(i);
					}
					int i = 0;
					for (ShoppieObject item : dataMerchants) {
						Merchant merchantItem = (Merchant) item;
						merchantItem.getValues();
						System.out.println("load merchant:" + merchantItem.merchImage);
						if (merchantItem.merchId == null)
							continue;
						item.getBitmap(getApplicationContext(), ((Merchant) item).merchImage);
						for (String value : merchantItem.getValues()) {
							System.out.print(value);
						}

						mcMng.insertNewTo(merchantItem.getValues());
						i++;
					}
					System.out.println("insert Merchant:" + i);
				} catch (ClientProtocolException e) {
					if (SettingPreference.PRINT_STACK_TRACE)
						e.printStackTrace();
					System.out.println(e.toString());
				} catch (IOException e) {
					if (SettingPreference.PRINT_STACK_TRACE)
						e.printStackTrace();
					System.out.println(e.toString());
				} catch (NullPointerException e) {
					if (SettingPreference.PRINT_STACK_TRACE)
						e.printStackTrace();
					System.out.println(e.toString());
				}

				return false;
			}
		}.execute();
	}

	// MAPVIEW
	@Override
	protected boolean isRouteDisplayed() {
		return true;
	}

	/*
	 * Navigates a given MapView to the specified Longitude and Latitude
	 * 
	 * @param latitude
	 * 
	 * @param longitude
	 * 
	 * @param mv
	 */
	public static void navigateToLocation(double latitude, double longitude, MapView mv) {
		GeoPoint p = new GeoPoint((int) latitude, (int) longitude); // new
		// GeoPoint
		mv.displayZoomControls(true); // display Zoom (seems that it doesn't
		// work yet)
		MapController mc = mv.getController();
		mc.animateTo(p); // move map to the given point
		int zoomlevel = mv.getMaxZoomLevel(); // detect maximum zoom level
		mc.setZoom(zoomlevel - 1); // zoom
		mv.setSatellite(false); // display only "normal" mapview

	}

	// QUICK ACTION
	@Override
	public void onItemClick(QuickAction source, int pos, int actionId) {
		if (shopCrtClicked == null) {
			source.dismiss();
			return;
		}

		switch (actionId) {
		case ID_UP:
			int index = shopsOverlay.getIndexOverlay(shopCrtClicked);
			index++;
			if (index > shopsOverlay.getOverlays().size() - 1)
				index = 0;
			shopCrtClicked = shopsOverlay.getOverlays().get(index);
			myMapController.animateTo(shopCrtClicked.getPoint());
			break;
		case ID_DOWN:
			int indexd = shopsOverlay.getIndexOverlay(shopCrtClicked);
			indexd--;
			if (indexd <= 0)
				index = shopsOverlay.getOverlays().size() - 1;
			shopCrtClicked = shopsOverlay.getOverlays().get(indexd);
			myMapController.animateTo(shopCrtClicked.getPoint());
			break;
		case ID_ERASE:
			break;
		case ID_INFO:
			Intent brandIntent = new Intent(this, BrandActivity.class);
			brandIntent.putExtra(BrandActivity.MERCH_ID, shopCrtClicked.getStore().merchId);
			brandIntent.putExtra(BrandActivity.STORE, shopCrtClicked.getStore());
			startActivity(brandIntent);
			// AlertDialog.Builder dialog = new AlertDialog.Builder(this);
			// dialog.setTitle(shopCrtClicked.getTitle());
			// dialog.setMessage(shopCrtClicked.getSnippet());
			// dialog.show();
			break;
		case ID_OK:
			source.dismiss();
			break;
		default:
			break;
		}
	}

	ShopOverlayItem shopCrtClicked = null;

	@Override
	public void onTap(ShopOverlayItem item) {
		myMapController.animateTo(item.getPoint());
		quickAction.show(mMapShops);
		shopCrtClicked = item;
	}

	// LOCATION
	@Override
	public void onLocationChanged(Location location) {
		MainActivity.myLocation = new GeoPoint((int) (location.getLatitude() * 1E6), (int) (location.getLongitude() * 1E6));
		MainActivity.accurancy = location.getAccuracy();
		this.drawMyLocation(myLocation, MainActivity.accurancy);
		myMapController.animateTo(MainActivity.myLocation);
		Collections.sort(stores, new StoreComparator());
		if (mAdapterStore == null)
			mAdapterStore = new StoreAdapter(this, stores);
		mAdapterStore.notifyDataSetChanged();
	}

	@Override
	public void onProviderDisabled(String provider) {
		Log.e("provider disable", provider);
		Location location = mLocaMng.getLastKnownLocation(LocationManager.GPS_PROVIDER);

		if (location == null) {
			location = mLocaMng.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
			if (location == null) {
				location = mLocaMng.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
				if (location == null) {
					return;
				}
			}
		}
		MainActivity.myLocation = new GeoPoint((int) (location.getLatitude() * 1E6), (int) (location.getLongitude() * 1E6));
		MainActivity.accurancy = location.getAccuracy();
		this.drawMyLocation(myLocation, MainActivity.accurancy);
		myMapController.animateTo(MainActivity.myLocation);
	}
	
	private void getLastKnownLocation(){
		Location location = mLocaMng.getLastKnownLocation(LocationManager.GPS_PROVIDER);

		if (location == null) {
			location = mLocaMng.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
			if (location == null) {
				location = mLocaMng.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
				if (location == null) {
					return;
				}
			}
		}
		MainActivity.myLocation = new GeoPoint((int) (location.getLatitude() * 1E6), (int) (location.getLongitude() * 1E6));
		MainActivity.accurancy = location.getAccuracy();
		this.drawMyLocation(myLocation, MainActivity.accurancy);
		myMapController.animateTo(MainActivity.myLocation);
	}

	@Override
	public void onProviderEnabled(String provider) {
		Log.e("provider enable", provider);
		Location location = mLocaMng.getLastKnownLocation(LocationManager.GPS_PROVIDER);

		if (location == null) {
			location = mLocaMng.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
			if (location == null) {
				location = mLocaMng.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
				if (location == null) {
					return;
				}
			}
		}
		MainActivity.myLocation = new GeoPoint((int) (location.getLatitude() * 1E6), (int) (location.getLongitude() * 1E6));
		MainActivity.accurancy = mLocaMng.getLastKnownLocation(LocationManager.GPS_PROVIDER).getAccuracy();
		this.drawMyLocation(myLocation, MainActivity.accurancy);
		myMapController.animateTo(MainActivity.myLocation);
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		Log.e("status change", provider + status + extras.toString());
		Location location = mLocaMng.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		if (location == null) {
			location = mLocaMng.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
			if (location == null) {
				location = mLocaMng.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
				if (location == null) {
					return;
				}
			}
		}
		MainActivity.myLocation = new GeoPoint((int) (location.getLatitude() * 1E6), (int) (location.getLongitude() * 1E6));
		MainActivity.accurancy = mLocaMng.getLastKnownLocation(LocationManager.GPS_PROVIDER).getAccuracy();
		this.drawMyLocation(myLocation, MainActivity.accurancy);
		myMapController.animateTo(MainActivity.myLocation);
	}

	@Override
	public void onZoom(int oldZoom, int newZoom) {
		MainActivity.zoom = newZoom;
		// if (newZoom >= MainActivity.zoom_def) {
		// for (ShopOverlayItem item : shopsOverlay.getOverlays()) {
		// item.refreshDrawable(newZoom);
		// }
		// }
		shopsOverlay.refreshMarker(newZoom);
	}

	public float getDistanceInMiles(GeoPoint p1, GeoPoint p2) {
		double lat1 = ((double) p1.getLatitudeE6()) / 1e6;
		double lng1 = ((double) p1.getLongitudeE6()) / 1e6;
		double lat2 = ((double) p2.getLatitudeE6()) / 1e6;
		double lng2 = ((double) p2.getLongitudeE6()) / 1e6;
		float[] dist = new float[1];
		Location.distanceBetween(lat1, lng1, lat2, lng2, dist);
		return dist[0] * 0.000621371192f;
	}

	String KEY_LAST_POINT = "last_position";

	protected void onSaveInstanceState(Bundle outState) {
		outState.putInt(KEY_LAST_POINT, lastIndex);
	};

	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		lastIndex = savedInstanceState.getInt(KEY_LAST_POINT);
	};

	Toast mToast;

	public void showToast(String text) {
		if (mToast == null)
			mToast = Toast.makeText(this, text, Toast.LENGTH_SHORT);
		mToast.cancel();
		mToast.setText(text);
		mToast.show();
	}
}
